import { getToken, removeToken, setToken, removeInfoCook, setUserInfoCook } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import router from '@/router'
import { resetRouter } from '@/router/index'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  // 存Token
  setToken(state, playload) {
    state.token = playload
    setToken(playload)
  },
  // 移除Token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 存储用户信息
  setUserInFo(state, playlod) {
    state.userInfo = playlod
    setUserInfoCook(playlod)
  },
  // 移除用户信息
  removeInfo(state) {
    state.userInfo = {}
    removeInfoCook()
  }
}
const actions = {
  // 登录
  async login(context, playolad) {
    const result = await login(playolad)
    context.commit('setToken', result)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const result = await getUserInfo()
    const baseInfo = await getUserDetailById(result.userId)
    const allUserInfo = { ...result, ...baseInfo }
    context.commit('setUserInFo', allUserInfo)
    return allUserInfo
  },

  // 退出登录
  logout(context) {
    context.commit('removeToken')
    context.commit('removeInfo')
    resetRouter()
    context.commit('permission/setRoutes', [], { root: true })
    router.push('/login')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
